<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
	<head>
		<jsp:include page="../inc.jsp"></jsp:include>
		<script type="text/javascript" src="../My97DatePicker/WdatePicker.js"></script>
		<script type="text/javascript" charset="utf-8">
		var lastIndex,id = '${id}',isConfirm = null,ridValue;	
		var tempid;
		var tempnum = 1;
		var tempbarcode = new Array();
		$(function() {
			var rid = $('#damageForm').find('input[name=rid]');
			var ridCombobox = rid.combobox({
				url : '${pageContext.request.contextPath}/rkgl/repertoryAction!noAuth_combobox.html',
				valueField : 'id',
				textField : 'name',
				multiple : false,
				editable : false,
				panelHeight : 'auto',
				onSelect : function(record){
					if(ridValue != record.id){
						$('#uid').combobox('reload',"${pageContext.request.contextPath}/qxgl/userAction!noAuth_userInReperCombobox.html?reid="+record.id);
						$('#dg').datagrid('loadData', { total: 0, rows: [] });
						sumNum();
					}
					ridValue = record.id;
				}
			});
			
			var uid = $('#damageForm').find('input[name=uid]');
			var uidCombobox = uid.combobox({
				url : '${pageContext.request.contextPath}/qxgl/userAction!noAuth_userInReperCombobox.html',
				valueField : 'id',
				textField : 'username',
				multiple : false,
				editable : false,
				panelHeight : 'auto',
				onLoadSuccess : function(){
					uid.combobox('setValue','${sessionInfo.userId}');
				}
			});
			
			$.ajax({
				url : '${pageContext.request.contextPath}/kcgl/goodsDamageAction!noAuth_search.html',
				data : {id : id},
				type : "POST",
				success : function(d){
					var json = $.parseJSON(d);
					var f = $('#damageForm');
					f.form("load",{
						id : json[0].id,
						date : json[0].date,
						serial : json[0].serial,
						uid : json[0].uid,
						rid : json[0].rid,
						num : json[0].num,
						remark :json[0].remark,
						total:json[0].total
					});
					isConfirm = json[0].isConfirm;
					
					var toolbar = [],onClickRow = function(rowIndex){};
					if(!isConfirm){
						toolbar = [{
							text: '确定',
							iconCls:'icon-edit',
							handler:function(){
								$('#dg').datagrid('acceptChanges');
								$('#dg').datagrid('beginEdit', lastIndex);
								var rows = $('#dg').datagrid('getRows');
								var row = rows[lastIndex];
								var subTotal = getMultiply(row.num,row.showPrice);
								row.total = subTotal;
								
								$('#dg').datagrid('acceptChanges');
								sumNum();
							}
						},'-',{
							text: '删行',
							iconCls:'icon-remove',
							handler:function(){
								parent.sy.messagerConfirm('请确认','您将从表中删除所选的项目?',function(r){
									if(r){
										var row = $('#dg').datagrid('getSelected');
										if (row){
											var index = $('#dg').datagrid('getRowIndex', row);
											$('#dg').datagrid('deleteRow', index);
											lastIndex = undefined;
										}
										sumNum();
									}
								});
							}
						},'-',{
							text: '保存',
							iconCls:'icon-add',
							handler:function(){
								$('#dg').datagrid('acceptChanges');
								$('#dg').datagrid('beginEdit', lastIndex);
								var rows = $('#dg').datagrid('getRows');
								var row = rows[lastIndex];
								var subTotal = getMultiply(row.num,row.showPrice);
								row.total = subTotal;
									
								$('#dg').datagrid('acceptChanges');
								sumNum();
								
								if(!$('#damageForm').form("validate"))
									return;
								
								var rows = $('#dg').datagrid('getRows');
								if(rows.length<1){
									parent.sy.messagerAlert('提示', '您尚未添加要报损的商品及数量！', 'error');
									return;
								}
								
								parent.sy.messagerConfirm('请确认','您确认要报损这些商品?',function(r){
									if(r){
										var items = [];
										for ( var i = 0; i < rows.length; i++) {
											items.push(rows[i].id);
											items.push(rows[i].gid);
											items.push(rows[i].num);
											items.push(rows[i].total);
										}
										$('#items').val(items.join(','));
										$('#id').val(id);
										alert('${id}');
										$('#damageForm').form('submit', {
											url : '${pageContext.request.contextPath}/kcgl/goodsDamageAction!edit.html',
											success : function(d) {
												var json = $.parseJSON(d);
												parent.sy.messagerShow({
													msg : json.msg,
													title : '提示'
												});
												if (json.success) {
													parent.showTab("添加库存报损单","库存报损");
												}
											}
										});
									}
								});
							}
						}],
					/*	onBeforeLoad:function(){
							$(this).datagrid('rejectChanges');
						}*/
						onClickRow = function(rowIndex){
							/*$('#dg').datagrid('endEdit', lastIndex);
							$('#dg').datagrid('beginEdit', lastIndex);
							
							var rows = $('#dg').datagrid('getRows');
							var row = rows[lastIndex];
							var subTotal = getMultiply(row.num,row.showPrice);
							row.total = subTotal;*/
							
							if(lastIndex!=rowIndex){
								$('#dg').datagrid('endEdit', lastIndex);
								$('#dg').datagrid('beginEdit', rowIndex);
							}else{
								$('#dg').datagrid('endEdit', lastIndex);
								$('#dg').datagrid('beginEdit', rowIndex);
							}
							
							lastIndex = rowIndex;
							sumNum();
						};
					}else{
						$('#searchForm').hide();
					}
					
					$('#dg').datagrid({
						url : '${pageContext.request.contextPath}/kcgl/goodsDamageItemAction!noAuth_datagrid.html?id='+id,
						//idField : 'id',
						toolbar:toolbar,
						onBeforeLoad:function(){
							$(this).datagrid('rejectChanges');
						},
						onClickRow:onClickRow
					});
					$("#barcode").live("keypress",function(e) {
						var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
						if (keyCode == 13) {
							_search();
							return false;
						}
					});
				}
			});
		});
			
			
	
		function _search() {
			var rid = $('#damageForm').find('input[name=rid]');
			if(rid.val().length<1){
				parent.sy.messagerAlert('提示', '请先选择报损的仓库！', 'error');
				return;
			}
			if($('#searchForm').find('input[name=barcode]').val().length<1){
				return;
			}
			$('#searchForm').find('input[name=rid]').val(rid.val())
			$('#searchForm').form('submit', {
				url : '${pageContext.request.contextPath}/spgl/goodsAction!noAuth_search_return.html',
				success : function(d) {
					var json = $.parseJSON(d);
				   if(json.success!=false){
				   var rows = $('#dg').datagrid('getRows');
					 var flag = 0;	
					    if(rows.length > 0){ 
					      lastIndex = rows.length-1;
					        for(var i = 0; i < rows.length; i++) {
					            var tempbarcode = $('#barcode').val();
					            if(tempbarcode == rows[i].barcode){	
					                tempnum = rows[i].num + 1;		   
					                $('#dg').datagrid('updateRow',{
	                                    index: i,
	                                    row: {
		                                      num: tempnum
	                                    }
                                    });					                
					                flag = 1;
					                tempnum = 1;
					                return false;
					            }					            
						    }	
						    lastIndex = rows.length-1;
							$('#dg').datagrid('selectRow', lastIndex);				        
					    }
					   if(flag == 0){
						$('#dg').datagrid('endEdit', lastIndex);
						$('#dg').datagrid('appendRow',{
						    gid:json.id,
							barcode:json.barcode,
							name:json.name,
							type:json.type,
							bname:json.bname,
							showPrice:json.showPrice,
							unit:json.unit,
							color:json.color,
							size:json.size,
							amount:json.amount,
							num:tempnum,
							total:Number(json.showPrice)*1
						});
						lastIndex = $('#dg').datagrid('getRows').length-1;
						$('#dg').datagrid('selectRow', lastIndex);
						 }					    
						return false;
					}else{
						parent.sy.messagerShow({
									msg : json.msg,
									title : '提示'
						});
					}
					sumNum();
				}
			});
// 			cleanSearch();
		}
		
		function cleanSearch() {
			$('#searchForm input').val('');
		}
		
		function sumNum(){
			var rows = $('#dg').datagrid('getRows');
			var sum = 0;
			for ( var i = 0; i < rows.length; i++) {
				sum = getSum(sum,rows[i].total);
			}
			$('#num').val(sum);
		}
		
		function getMultiply(a,b){
			if((Number(a)+"")=="NaN"||(Number(a)+"")=="NaN"){
				return 0;
			}
			
			var n = 0,numbera = Number(a),numberb = Number(b),a=a+"",b=b+"";
			
			var indexa = a.indexOf(".");
			var lengtha = a.length;
			if(indexa != -1){
				n+= lengtha-indexa-1;
				var stra = a.substring(0,indexa)+a.substring(indexa+1,lengtha)
				numbera = Number(stra);
			}
			
			var indexb = b.indexOf(".");
			var lengthb = b.length;
			if(indexb != -1){
				n+= lengthb-indexb-1;
				var strb = b.substring(0,indexb)+b.substring(indexb+1,lengthb)
				numberb = Number(strb);
			}
			
			var multiply = (numbera*numberb);
			multiply+="";
			var lengthm = multiply.length;
			if(n==0){
				return multiply;
			}else if(lengthm>n){
				return multiply.substring(0,lengthm-n)+"."+multiply.substring(lengthm-n,lengthm);
			}else{
				var temp = "";
				for(var i = 0;i<lengthm-n;i++){
					temp+="0";
				}
				return "0."+temp+multiply;
			}
		}
		
		function getSum(a,b){
			if((Number(a)+"")=="NaN"||(Number(a)+"")=="NaN"){
				return 0;
			}
			
			var n = 0,na = 0,nb = 0,numbera = Number(a),numberb = Number(b),a=a+"",b=b+"";
			
			var indexa = a.indexOf(".");
			var lengtha = a.length;
			var stra = a;
			if(indexa != -1){
				na = lengtha-indexa-1;
				stra = a.substring(0,indexa)+a.substring(indexa+1,lengtha)
			}
			
			var indexb = b.indexOf(".");
			var lengthb = b.length;
			var strb = b;
			if(indexb != -1){
				nb = lengthb-indexb-1;
				strb = b.substring(0,indexb)+b.substring(indexb+1,lengthb)
			}
			
			if(na>0&&nb>0){
				if(na>=nb){
					n = na;
					numbera = Number(stra);
					var temp = "";
					for(var i = 0;i<na-nb;i++){
						temp+="0";
					}
					numberb = Number(strb+temp);
				}else if(na<nb){
					n = nb;
					numberb = Number(strb);
					var temp = "";
					for(var i = 0;i<nb-na;i++){
						temp+="0";
					}
					numbera = Number(stra+temp);
				}
			}else if(na>0){
				n = na;
				numbera = Number(stra);
				var temp = "";
				for(var i = 0;i<na;i++){
					temp+="0";
				}
				numberb = Number(strb+temp);
			}else if(nb>0){
				n = nb;
				numberb = Number(strb);
				var temp = "";
				for(var i = 0;i<nb;i++){
					temp+="0";
				}
				numbera = Number(stra+temp);
			}else{
				numbera = Number(stra);
				numberb = Number(strb);
			}
			
			var sum = numbera+numberb;
			sum+="";
			var lengthm = sum.length;
			if(n==0){
				return sum;
			}else if(lengthm>n){
				return sum.substring(0,lengthm-n)+"."+sum.substring(lengthm-n,lengthm);
			}else{
				var temp = "";
				for(var i = 0;i<lengthm-n;i++){
					temp+="0";
				}
				return "0."+temp+sum;
			}
		}
	</script>
	</head>
	<body class="easyui-layout" data-options="fit:true">
	
		<div data-options="region:'north',border:false" style="height: 140px; overflow: hidden;">
			<form id="damageForm" style="height:110px;">
				<input id="items" name="items" type="hidden" />
				<input id="id" name="id" type="hidden" />
				<table class="tableForm datagrid-toolbar" style="width: 100%; height: 100%;">
					<tr>
						<th style="width: 50px;">日&nbsp;&nbsp;&nbsp;&nbsp;期</th>
						<td style="width: 200px;"><input name="date" id="datebox" class="Wdate" onclick="WdatePicker()" style="width: 200px;" data-options="required:'true',missingMessage:'请输入调拔日期'"/></td>
						<th style="width: 50px;">单&nbsp;&nbsp;&nbsp;&nbsp;号</th>
						<td style="width: 200px;"><input name="serial" style="width: 200px;" readonly="readonly" id="serial"/></td>
						<th style="width: 50px;">仓库名称 </th>
						<td style="width: 200px;"><input name="rid" id="rid" style="width: 200px;" data-options="required:'true',missingMessage:'请选择调入仓库'"/></td>
					</tr>
					<tr>
						<th style="width: 50px;">营&nbsp;业&nbsp;员</th>
						<td style="width: 200px;"><input name="uid" id="uid" style="width: 200px;" data-options="required:'true',missingMessage:'请选择操作员'"/></td>
						<th>报损总额</th>
						<td colspan="3"><input name="total" id="num" style="width: 200px;" type="text" readonly="readonly"/></td>
					</tr>
					<tr>
						<th>备&nbsp;&nbsp;&nbsp;&nbsp;注</th>
						<td colspan="5"><textarea name="remark" style="height:30px;width: 85%;"></textarea></td>
					</tr>
				</table>
			</form>
			
			<form id="searchForm" style="height:10px;margin-top:0px;">
				<input type="hidden" name="rid" value="" id="searchRid"/>
				<table class="tableForm datagrid-toolbar" style="width: 100%; height: 100%;">
					<tr>
						<th style="width: 58px;">商品条码</th>
						<td style="width: 220px;"><input name="barcode"  id="barcode" style="width: 200px;" /></td>
<!-- 						<th style="width: 70px;">款&nbsp;&nbsp;&nbsp;&nbsp;号</th> -->
<!-- 						<td style="width: 220px;"><input name="type" style="width: 200px;" /></td> -->
						<td style="width: 280px;" align="right" colspan="4">
							<a href="javascript:void(0);" class="easyui-linkbutton" onclick="_search();">定位商品</a>
							<a href="javascript:void(0);" class="easyui-linkbutton" onclick="cleanSearch();">取消</a>
						</td>
					</tr>
				</table>
			</form>
		</div>
	
		<div data-options="region:'center',border:false" style="overflow: hidden;">
			<table id="dg" class="easyui-datagrid" style="height:auto"  data-options="iconCls: 'icon-edit',singleSelect: true">  
		        <thead>
		            <tr>
		            	<th data-options="field:'id',width:50,hidden:true">明细ID</th>  
		            	<th data-options="field:'gid',width:50,hidden:true">商品ID</th>  
		            	<th data-options="field:'barcode',width:120">商品条码</th>
		                <th data-options="field:'type',width:80">款号/款式</th>  
		                <th data-options="field:'bname',width:80">品牌</th>
	                 	<th data-options="field:'gname',width:80">商品名称</th>
	                  	<th data-options="field:'unit',width:50">单位</th>
                   		<th data-options="field:'color',width:60">颜色</th>
                   		<th data-options="field:'size',width:60">尺码</th>
                   		<th data-options="field:'showPrice',width:80">吊牌价</th>
                   		<th data-options="field:'amount',width:60">库存</th>
		                <th data-options="field:'num',width:80,align:'center',editor:{type:'numberbox'}">报损数量</th>
		                <th data-options="field:'total',width:80,">报损总额</th>
		            </tr>
		        </thead>
		    </table>
		</div>
	</body>
</html>